package datapack

import (
	"broker/interface/imodel"
	"broker/struct/model"
	"encoding/binary"
)

/**
 * @Description
 * @Author huan.wang
 * @Date 2021/4/26 10:54 下午
 **/

type SubscribeDataPack struct {
}

func NewSubscribeDataPack() *SubscribeDataPack {
	return &SubscribeDataPack{}
}

func (s SubscribeDataPack) Pack(message imodel.IMessage) ([]byte, error) {
	panic("implement me")
}

func (s SubscribeDataPack) UnPack(bytes []byte) (imodel.IMessage, error) {
	subMsg := model.NewSubscribeMessage()
	pdp := NewParamDataPack(bytes)
	paramData, err := pdp.UnPackByLen(2)
	if err != nil {
		return nil, err
	}
	binary.Read(paramData.GetDataBuffer(), binary.BigEndian, &subMsg.PacketID)
	for {
		filterData, err := pdp.UnPack()
		if err != nil {
			break
		}
		qosData, err := pdp.UnPackByLen(1)
		if err != nil {
			break
		}
		topicFilter := model.NewTopicFilter(string(filterData.GetData()), qosData.GetData()[0])
		subMsg.AddTopicFilter(topicFilter)
	}
	return subMsg, nil

}
